import React, { useRef, useState, useEffect } from 'react';
import { MapPin, Navigation, Layers, Plus, Minus } from 'lucide-react';

// 为window对象添加AMap类型声明
declare global {
  interface Window {
    AMap: any;
  }
}

type MapProps = {
  center?: { lat: number; lng: number };
  zoom?: number;
  markers?: Array<{
    id: string;
    lat: number;
    lng: number;
    title?: string;
    onClick?: () => void;
  }>;
  onMapClick?: (lat: number, lng: number) => void;
};

const MapComponent: React.FC<MapProps> = ({ 
  center = { lat: 39.90923, lng: 116.397428 }, // 默认北京
  zoom = 13,
  markers = [],
  onMapClick
}) => {
  const mapRef = useRef<HTMLDivElement>(null);
  const [map, setMap] = useState<any>(null);
  const [loaded, setLoaded] = useState(false);

  // 动态加载高德地图API
  useEffect(() => {
    if (window.AMap) {
      setLoaded(true);
      return;
    }

    const script = document.createElement('script');
    script.src = 'https://webapi.amap.com/maps?v=2.0&key=049cae6b11b1912b195aa5e615ea799b'; // 已替换为真实密钥
    script.onload = () => {
      setLoaded(true);
    };
    script.onerror = (error) => {
      console.error('高德地图API加载失败:', error);
    };

    document.head.appendChild(script);

    return () => {
      document.head.removeChild(script);
    };
  }, []);

  // 初始化地图
  useEffect(() => {
    if (!loaded || !mapRef.current) return;

    // 创建地图实例
    const newMap = new window.AMap.Map(mapRef.current, {
      zoom,
      center: [center.lng, center.lat],
      resizeEnable: true
    });

    // 添加控件
    newMap.plugin(['AMap.ToolBar', 'AMap.Scale'], () => {
      newMap.addControl(new window.AMap.ToolBar());
      newMap.addControl(new window.AMap.Scale());
    });

    // 添加标记
    markers.forEach(marker => {
      const mapMarker = new window.AMap.Marker({
        position: [marker.lng, marker.lat],
        title: marker.title,
        map: newMap
      });

      if (marker.onClick) {
        mapMarker.on('click', marker.onClick);
      }
    });

    // 地图点击事件
    if (onMapClick) {
      newMap.on('click', (e: any) => {
        onMapClick(e.lnglat.getLat(), e.lnglat.getLng());
      });
    }

    setMap(newMap);

    return () => {
      newMap.destroy();
    };
  }, [loaded, center, zoom, markers, onMapClick]);

  // 地图控制函数
  const handleZoomIn = () => {
    if (map) map.zoomIn();
  };

  const handleZoomOut = () => {
    if (map) map.zoomOut();
  };

  const handleLocation = () => {
    if (map) {
      map.plugin('AMap.Geolocation', () => {
        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true
        });

        map.addControl(geolocation);
        geolocation.getCurrentPosition();

        window.AMap.event.addListener(geolocation, 'complete', (data: any) => {
          console.log('定位成功:', data);
        });

        window.AMap.event.addListener(geolocation, 'error', (data: any) => {
          console.error('定位失败:', data);
        });
      });
    }
  };

  return (
    <div className="relative w-full h-full">
      <div ref={mapRef} className="w-full h-full bg-gray-100"></div>

      {/* 地图控制按钮 */}
      <div className="absolute top-4 right-4 flex flex-col gap-2 bg-white rounded-lg shadow-lg p-1">
        <button 
          className="p-2 rounded hover:bg-gray-100 transition-colors" 
          onClick={handleZoomIn}
          aria-label="放大"
        >
          <Plus className="h-5 w-5 text-gray-700" />
        </button>
        <button 
          className="p-2 rounded hover:bg-gray-100 transition-colors" 
          onClick={handleZoomOut}
          aria-label="缩小"
        >
          <Minus className="h-5 w-5 text-gray-700" />
        </button>
        <div className="border-t border-gray-200 my-1"></div>
        <button 
          className="p-2 rounded hover:bg-gray-100 transition-colors" 
          onClick={handleLocation}
          aria-label="定位"
        >
          <Navigation className="h-5 w-5 text-gray-700" />
        </button>
        <button 
          className="p-2 rounded hover:bg-gray-100 transition-colors" 
          aria-label="图层"
        >
          <Layers className="h-5 w-5 text-gray-700" />
        </button>
      </div>
    </div>
  );
};

export default MapComponent;